package com.example.utils;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by alading-qs on 2016/12/27.
 */
public class IpUtil {

    private static final String UNKNOWN = "unknown";

    public IpUtil() {
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip != null && ip.indexOf(44) > 7) {
            ip = ip.split(",")[0];
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        return ip == null ? request.getRemoteAddr() : ip;
    }
}
